package com.zxjbyte.yiyi.framework.common.domain;

import com.zxjbyte.yiyi.framework.common.util.JsonUtil;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;
import java.util.Objects;

/**
 * 键值对Bean
 * @Author zhangxingjia
 * @Date 2023/3/15 17:12
 * @Version: 1.0
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class KeyValue<K, V> implements Serializable {
    private static final long serialVersionUID = 1L;

    protected K key;
    protected V value;

    public static <K, V> KeyValue<K, V> create() {
        return new KeyValue<>();
    }

    public static <K, V> KeyValue<K, V> of(K key, V value) {
        return new KeyValue<>(key, value);
    }

    /**
     * 获取对象根据指定索引
     * @param index
     * @return
     */
    public Object get(int index) {
        switch (index) {
            case 0:
                return key;
            case 1:
                return value;
            default:
                return null;
        }
    }

    public String toJosnString(){
        return JsonUtil.toJsonAsString(this);
    }

    @Override
    public String toString() {
        return getClass().getSimpleName() + " [key=" + key + ", value=" + value + "]";
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true; // 自反性
        if (o == null || getClass() != o.getClass()) return false; // 类型严格一致
        KeyValue<?, ?> that = (KeyValue<?, ?>) o;
        return Objects.equals(key, that.key) && Objects.equals(value, that.value); // 比较字段
    }

    @Override
    public int hashCode() {
        return Objects.hash(key, value);
    }

}
